<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Api\Utils\QrcodeUtil;

class DistributionShopController extends BackgroundController {
	
	public function _initialize() {
		$this->setControllerTitle('分销商城信息设置');
		$this->setActionTitle(array(
				'index' => '分销商城信息',
				'config' => '分销商城配置',
				'wechat' => '分销微信回复设置',
				'url' => '分销商城地址',
				'certUrl' => '证书查询地址',
				'qrcode' => '商城宣传二维码模板设置',
		        'agentShopConfig' => '代理版商城配置',
		));
		$this->setActionNav('index,config,wechat,url,certUrl,qrcode');
		$this->assign('cid', $this->aid);
	}
	
	// 商城信息
	public function indexAction() {
		$dProduct = D('DistributionShop');
		$product = $dProduct->find($this->aid);
		if (!$product) {
			$data = array(
					'id' => $this->aid,
					'cid' => $this->aid,
					'name' => $this->aname 
			);
			if (!$dProduct->add($data)) {
				$this->error('添加商城信息失败');
			}
			$product = $dProduct->find($this->aid);
		}
		$product['status'] = $this->getRadio('status', $dProduct->status, $product['status']);
		$product['donate_on'] = $this->getRadio('donate_on', $dProduct->donate_on, $product['donate_on']);
		$product['openInBrowser'] = $this->getRadio('openInBrowser', array(0=>'在微信中',1=>'在浏览器中'),$product['openInBrowser']);
		$product['user_discount'] and $product['user_discount'] = unserialize($product['user_discount']);
		$product['rewardBonusType'] = $this->getRadio('reward_bonus_type', array(0=>'现金',1=>'商城币(确定分销返币行为已开启)',2=>'现金与商城币(确定分销返币积分项已开启,1元返1商城币)'), $product['reward_bonus_type']);
		/* 角色等级开关 */
		$showLevelConfig = array();
		if ( $product['level_config']) {
		    $product['level_config'] = unserialize($product['level_config']);
		} else {
		    $product['level_config'] = array();
		}
		$distributionShopJobTitleList = M("DistributionShopJobTitle")->select();
		foreach ( $distributionShopJobTitleList as $v ) {
		    $showLevelConfig[$v['id']] = array(
		        'name' => $v['name'],
		        'hasLevel' => $product['level_config'][$v['id']]*1,
		        'radioOption' => $this->getRadio("level_config[{$v['id']}]", array('0' => '关闭', '1' => '开启'), $product['level_config'][$v['id']]*1),
		    );
		}
		$product['level_config'] = $showLevelConfig;
		$this->assign('product', $product);
		$this->display('save');
	}
	
	// 首页地址
	public function urlAction() {
		$product = M('DistributionShop')->find($this->aid);
		$product['url'] = uu($this->aid, 'Home', 'DisShop', 'index', "sid={$this->aid}", true);
		$this->assign('product', $product);
		$this->display();
	}
	
	// 证书查询地址
	public function certUrlAction() {
		$product = array();
		$product['url'] = url('Home', 'DisShopCertificate', 'search', "sid={$this->aid}", true);
		$this->assign('product', $product);
		$this->display();
	}
	
	/**
	 * 二维码宣传模板设置
	 */
	public function qrcodeAction() {
		$product = M('DistributionShop')->find($this->aid);
		$config = unserialize($product['qr_config']);
		empty($product['qr_config']) or empty($config) ? $config = array() : $config ;
		$this->assign("qrConfig", $config);
		$this->assign("fieldsConfig", json_encode(QrcodeUtil::$fieldsConfig));
		$this->assign("qrConfigJson", $config ? json_encode($config) : "{}");
		$this->display();
	}
	
	public function qrcodePostAction() {
		$m = M('DistributionShop');
		$product = $m->find($this->aid);
		$config = I("qr_config", array());
		$product['qr_config'] = serialize($config);
		if ( false !== $m->save( $product ) ) {
			$this->ajaxSuccess('保存成功');
		}
		$this->ajaxError('保存失败');
	}
	
	// 微信回复设置
	public function wechatAction() {
		$wechat_rule = '__distribution_shop_rule__';
		$d = D('WechatReply');
		$reply = $d->getReply($this->aid, $wechat_rule);
		if (!$reply) {
			$url = url('Home', 'DisShop', 'index', 'sid=' . $this->aid, true);
			$id = $d->setKeywordReply($this->aid, $wechat_rule, '微分销', '微分销', '点击进入【微分销】', '', $url);
			$id && $reply = $d->find($id);
		}
		$reply['keyword'] = trim($reply['keyword'], ' ,');
		$this->assign('reply', $reply);
		$this->display();
	}
	
	// 提交微信回复
	public function wechatPostAction() {
		$d = D('WechatReply');
		if ($d->create()) {
			$d->keyword = $d->parseKeyword($d->keyword);
			if ($d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	// 商城配置
	public function configAction() {
		$dProduct = D('DistributionShop');
		$product = $dProduct->find($this->aid);
		if ( $product ) {
		    $config = $dProduct->extendsConfig;
			$product['config'] = unserialize( $product['config'] );
			foreach ($config as $k => &$v) { // 生成html
				if ( $v['type'] == 'radio' ) {
				    $v['html'] = $this->getRadio('config['.$v['name'].']', $v['data'], $product['config'][$k]['value'] );
				} elseif( $v['type'] == 'textEditor' ) {
				    $html .= <<<'PARSE'
	<textarea id='config[{fieldName}]' name='config[{fieldName}]'>{fieldValue}</textarea>
    <!-- ueditor -->
    <link rel="stylesheet" href="/ue/themes/default/css/ueditor.min.css">
    <script type="text/javascript" src="/ue/ueditor.config.js"></script>
    <script type="text/javascript" src="/ue/ueditor.all.js"></script>
    <script type="text/javascript">
      window.UEDITOR_HOME_URL = "/ue/";
        var editor = UE.getEditor("config[{fieldName}]", {
          initialFrameWidth: "100%",
          initialFrameHeight: 300,
          textarea: "config[{fieldName}]"
        });
    </script>
PARSE;
				    $r = array(
				        '{fieldName}'=>$v['name'],
				        '{fieldValue}'=>$product['config'][$k]['value'],
				    );
				    $html = str_replace(array_keys($r), array_values($r), $html);
				    $v['html'] = $html;
				}
			}
			$product['config'] = $config;
		}
		$this->assign("product", $product);
		$this->display();
	}

    /**
     * 代理分佣模式二生成分佣比例
     */
//     private function getRewardModelTwoPercent( $level ) {
//         $newArray = array();
//         $this->loop(0, $level, $arr, $newArray);
//         return $newArray;
//     }	

	/**
	 * 代理分佣模式二生成分佣比例 
	 */
    private function getRewardModelTwoPercent( $level ) {
        $percent = array();
        $level and $percent[0][-1] = "0";
        for ( $i=0; $i<=($level?$level-1:-1); $i++ ) {
            for ( $j=0; $j<$level; $j++ ) { // for ( $j=$i; $j<=((($i+1)<$level)?$i+1:$i); $j++ ) {
                $percent[$i][$j]="0:0";
            }
            $percent[$i] = (is_array($percent[$i]) ? (object)$percent[$i] : $percent[$i]);
        }
        return $percent;
    }
    
    /**
     * 代理多级分等级分佣
     * @param unknown $level
     * @return multitype:string
     */
    private function getRewardModelThreePercent( $level ) {
        $arr = array_fill(0, $level, 0);
        if ( !function_exists("loop") ) {
            function loop($j, $loopTimes, &$arr, &$newArray, $level = 0, $path = "")
            {
                if ($j == count($arr)) {
                    return;
                }
                while ($arr[$j]<$loopTimes)
                {
                    $temp = $path.".$arr[$j]";
                    $newArray[trim($temp, ".")] = join(':', array_fill(0, count(explode('.', trim($temp, "."))), 0));
                    loop($j + 1, $loopTimes, $arr, $newArray, $level+1, $path.".$arr[$j]");
                    $arr[$j]++;
                    if ($j + 1 < count($arr)) $arr[$j + 1] = 0;
                }
            }            
        }
        $newArray = array();
        loop(0, $level, $arr, $newArray);
        return $newArray;
    }
    
    public function loop($j, $loopTimes, &$arr, &$newArray)
    {
        if ($j == count($arr)) {
            $newArray = join(":", array_fill(0, $j, 0));;
            return;
        }
        while ($arr[$j]<$loopTimes)
        {
            $newArray[$arr[$j]] = array();
            $newArray[$arr[$j]][-1] = join(":", array_fill(0, $j+1, 0));
            $this->loop($j + 1, $loopTimes, $arr, $newArray[$arr[$j]]);
            $arr[$j]++;
            if ($j + 1 < count($arr)) $arr[$j + 1] = 0;
        }
    }
    

	
	/**
	 * 代理商城配置
	 */
	public function agentShopConfigAction() {
	    $d = D('DistributionShop');
	    $distributionShop = $d->find($this->aid);
	    if ( $distributionShop ) {
	       $distributionShop['agent_shop_config'] and $distributionShop['agent_shop_config'] = unserialize( $distributionShop['agent_shop_config'] );
	       if ( !$distributionShop['agent_shop_config'] ) {
	           $distributionShop['agent_shop_config'] = array(
	               'enabled' => 0, // 是否启用代理商城
	               'agentNotStock' => 0, // 是否启用代理分红
	               'level' => 3, // 代理商级数
	               'rewardMode' => 0, // 代理分佣方案类型
	               'modeConfig' => array(
	                   '0' => array( // 分佣方案一的配置
	                       'agent_reward_percent' => '',
	                   ),
	                   '1' => array(
	                       'agent_reward_percent' => $this->getRewardModelTwoPercent(3),
	                   ),
	                   '2' => array(
	                       'agent_reward_percent' => $this->getRewardModelThreePercent(3),
	                   ),
	               )
	           );
	       } else {
	           // 模式二配置
	           if ( isset($distributionShop['agent_shop_config']['modeConfig'][1]) ) {
	               $modeOneConfig = &$distributionShop['agent_shop_config']['modeConfig'][1];
	               /* 输出页面时转对象 */
	               foreach ( $modeOneConfig['agent_reward_percent'] as $k => $v ) {
	                   $modeOneConfig['agent_reward_percent'][$k] = (is_array($v) ? (object)$v : $v);
	               }
	           }
	       }
	       $this->assign("agentShopConfig", $distributionShop['agent_shop_config']);
	    } else {
	        exit('请先完成商城基础配置');
	    }
	    $this->display();
	}
	
	/**
	 * 保存代理商城配置
	 */
	public function saveAgentShopConfigAction() {
	    $config = I("agentShopConfig", array());
	    if ( $config ) {
	        $config['enabled'] = $config['enabled'] == 'true' ? true : false;
	        $config['agentNotStock'] = $config['agentNotStock'] == 'true' ? true : false;
	        $config['show_agent_name'] = $config['show_agent_name'] == 'true' ? true : false;
	    } 
	    $d = D('DistributionShop');
	    false !== $d->where(array('cid' => $this->aid))->save(array(
	        'agent_shop_config' => serialize($config),
	    )) and $this->ajaxSuccess("保存成功");
	    $this->ajaxError("保存失败");
	}
	
	/**
	 * 分销商城配置
	 * @see \Utuo\BackgroundController::saveAction()
	 */
	public function saveAction() {
		$rewardPercent = I("reward_percent");
		$baseLevels = I("base_levels");
		if( empty($baseLevels) ) {
			$_POST['reward_percent'] = "";
		} else {
			if ( array_sum(explode(':', $rewardPercent)) != 100 ) {
				$this->ajaxError('基础佣金分成比例之和必须等于100%');
			}
		}

		$rewardPercent = I("reward_percent_dealer");
		$dealerLevels = I("dealer_levels");
		if( empty($dealerLevels) ) {
			$_POST['reward_percent_dealer'] = "";
		} else {
			if ( array_sum(explode(':', $rewardPercent)) != 100 ) {
				$this->ajaxError('特约经销商佣金分成比例之和必须等于100%');
			}
		}
		
		$requiredSubscribe = I("buy_required_subscribe", 0);
		$_POST['buy_required_subscribe'] = $requiredSubscribe ? true : false;
		
		$requiredSubscribe = I("discount_open", 0);
		$_POST['discount_open'] = $requiredSubscribe ? true : false;
		
		parent::saveAction();
	}
	
}